package com.chaoyue.content.service.impl;


import com.chaoyue.base.exception.ChaoYuePlusException;
import com.chaoyue.base.exception.CommonError;
import com.chaoyue.base.utils.JsonUtil;
import com.chaoyue.content.beans.dto.CourseBaseInfoDto;
import com.chaoyue.content.beans.dto.CoursePreviewDto;
import com.chaoyue.content.beans.dto.TeachplanDto;
import com.chaoyue.content.beans.po.CourseBase;
import com.chaoyue.content.beans.po.CourseMarket;
import com.chaoyue.content.beans.po.CoursePublish;
import com.chaoyue.content.beans.po.CoursePublishPre;
import com.chaoyue.content.config.MultipartSupportConfig;
import com.chaoyue.content.feignclient.MediaServiceClient;
import com.chaoyue.content.mapper.CourseBaseMapper;
import com.chaoyue.content.mapper.CourseMarketMapper;
import com.chaoyue.content.mapper.CoursePublishMapper;
import com.chaoyue.content.mapper.CoursePublishPreMapper;
import com.chaoyue.content.service.CourseBaseInfoService;
import com.chaoyue.content.service.CoursePublishService;
import com.chaoyue.content.service.TeachplanService;
import com.chaoyue.messagesdk.model.po.MqMessage;
import com.chaoyue.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@SuppressWarnings({"all"})
/**
 * @author whr
 * @version 1.0
 * @description: 课程预览 发布接口实现类
 * @date 2023/5/22 20:13
 */
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {
    @Autowired
    private CourseBaseInfoService courseBaseInfoService;
    @Autowired
    private TeachplanService teachplanService;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CoursePublishPreMapper coursePublishPreMapper;
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CoursePublishMapper coursePublishMapper;
    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private MediaServiceClient mediaServiceClient;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();

        CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.getCourseBaseInfoDto(courseId);
        coursePreviewDto.setCourseBase(courseBaseInfoDto);
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        coursePreviewDto.setTeachplans(teachplanTree);
        return coursePreviewDto;
    }

    //提交审核
    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {
        CourseBaseInfoDto courseBase = courseBaseInfoService.getCourseBaseInfoDto(courseId);
        if (courseBase == null) {
            ChaoYuePlusException.cast("课程不存在");
        }
        String pic = courseBase.getPic();
        String auditStatus = courseBase.getAuditStatus();

        if ("202003".equals(auditStatus)) {
            ChaoYuePlusException.cast("该课程已提交审核,再审核完成之后可再次提交审核");
        }
        if (!courseBase.getCompanyId().equals(companyId)) {
            ChaoYuePlusException.cast("不能提交审核其它机构的课程");
        }
        if (pic == null || "".equals(pic)) {
            ChaoYuePlusException.cast("提交失败,该课程还未设置封面");
        }
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBase, coursePublishPre);
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        String courseMarketJson = JsonUtil.objectTojson(courseMarket);
        coursePublishPre.setMarket(courseMarketJson);
        //课程计划
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        if (teachplanTree == null || teachplanTree.size() <= 0) {
            ChaoYuePlusException.cast("提交失败,还没有添加课程计划");
        }
        String teachplanTreeJson = JsonUtil.listTojson(teachplanTree);
        coursePublishPre.setTeachplan(teachplanTreeJson);
        //预发布记录状态
        coursePublishPre.setStatus("202003");
        //机构id
        coursePublishPre.setCompanyId(companyId);
        //创建时间
        coursePublishPre.setCreateDate(LocalDateTime.now());
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreUpdate == null) {
            coursePublishPreMapper.insert(coursePublishPre);
        } else {
            coursePublishPreMapper.updateById(coursePublishPre);
        }
        //更新课程基本信息表中的审核状态
        CourseBase courseBase1 = courseBaseMapper.selectById(courseId);
        courseBase1.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase1);
    }

    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {
        //从预发布表获取课程发布记录
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null) {
            ChaoYuePlusException.cast("课程未提交审核,发布失败");
        }
        String status = coursePublishPre.getStatus();
        //状态必须为审核通过
        if (!status.equals("202004")) {
            ChaoYuePlusException.cast("课程未通过审核,发布失败");
        }
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        CoursePublish coursePublishObj = coursePublishMapper.selectById(courseId);
        if (coursePublishObj == null) {
            coursePublishMapper.insert(coursePublish);
        } else {
            coursePublishMapper.updateById(coursePublish);
        }
        //写入发布任务消息表
       // saveCoursePublishMessage(courseId);
        //删除预发布表数据
        coursePublishPreMapper.deleteById(courseId);
    }

    @Override
    public File generateCourseHtml(Long courseId) {
        File htmlFile = null;
        try {
            Configuration configuration = new Configuration(Configuration.getVersion());

            //设置模板目录
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置编码
            configuration.setDefaultEncoding("utf-8");
            //获取模板
            Template template = configuration.getTemplate("course_template.ftl");
            //获取数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            HashMap<String, CoursePreviewDto> map = new HashMap<>();
            map.put("model", coursePreviewInfo);
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            htmlFile = File.createTempFile("courseTmp", ".html");
            InputStream inputStream = IOUtils.toInputStream(content);
            FileOutputStream fileOutputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (Exception ex) {
            log.error("课程静态化异常:{}", ex.toString());
            ChaoYuePlusException.cast("课程静态化异常");
        }
        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        try {
            String upload = mediaServiceClient.upload(multipartFile, "course/" + courseId + ".html");
            if (upload == null) {
                ChaoYuePlusException.cast("静态化文件上传失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            ChaoYuePlusException.cast("静态化文件上传失败");
        }
    }

    @Override
    public CoursePublish selectCoursePublishById(Long courseId) {
        return coursePublishMapper.selectById(courseId);
    }

    private void saveCoursePublishMessage(Long courseId) {
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if (mqMessage == null) {
            ChaoYuePlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }

}
